package org.example.oop.thread;

import lombok.SneakyThrows;

/**
 * org.example.oop.thread
 *
 * @author moLei
 * @description 线程死锁,线程1先获取锁A,运行一段时间后去获取锁B,线程2先获取锁B,运行一段时间后去获取锁A,线程1和线程2就会互相等待,造成死锁
 * @date 2025/6/22
 */
public class DieLockThreadDemo {

    static Object lockA = new Object();

    static Object lockB = new Object();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            @SneakyThrows
            public void run() {
                synchronized (lockA) {
                    System.out.println(Thread.currentThread().getName()+ "获取锁A");
                    Thread.sleep(1000);
                    synchronized (lockB) {
                        System.out.println("线程1获取锁A和B");
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            @SneakyThrows
            public void run() {
                synchronized (lockB) {
                    System.out.println(Thread.currentThread().getName()+ "获取锁B");
                    Thread.sleep(1000);
                    synchronized (lockA) {
                        System.out.println("线程2获取锁A和B");
                    }
                }
            }
        }).start();
    }
}
